import axios from 'axios';
import { ElNotification, ElMessage } from 'element-plus'
import errorCode from '@/utils/errorCode'
import { getItem } from '@/utils/stroge'
// 引入进度条
import nprogress from 'nprogress'
// 引入进度条样式
import 'nprogress/nprogress.css'

const instance = axios.create({
	timeout: 5000,
	baseURL: import.meta.env.VITE_APP_BASE_API
});
// 实例的请求拦截器
instance.interceptors.request.use(
	config => {
		nprogress.start()
		if (getItem('token')) {
			config.headers.Authorization = getItem('token')
		}
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 实例的响应拦截器
instance.interceptors.response.use(
	res => {
		nprogress.done()
		// 未设置状态码则默认成功状态
		const code = res.data.code || 200;
		// 获取错误信息
		const msg = errorCode[code] || res.data.msg || errorCode['default']

		// 二进制数据则直接返回
		if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
			return res
		}
		if(+code === 401){
			/**
			 * 未携带token和token失效都返401
			*/
			ElMessage({
				message: '无效的会话，或者会话已过期，请重新登录。',
				type: 'error'
			})
			return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
		}else if (+code === 500) {
			ElMessage({ message: msg, type: 'error' });
			return Promise.reject(new Error(msg));
		} else if (+code === 601) {
			ElMessage({ message: msg, type: 'warning' });
			return Promise.reject(new Error(msg));
		} else if (+code !== 200) {
			ElNotification.error({ title: msg });
			return Promise.reject('error');
		} else {
			return Promise.resolve(res.data);
		}
	},
	error => {
		nprogress.done()
		let { message } = error;
		if (message == "Network Error") {
			message = "后端接口连接异常";
		} else if (message.includes("timeout")) {
			message = "系统接口请求超时";
		} else if (message.includes("Request failed with status code")) {
			message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
		return Promise.reject(error)
	}
)

export default instance